'use strict';

/**
 * 门禁控制器指令发送
 */
const dgram = require('dgram');
const logger = require('../utils/logger');

// 假装单例
const client = dgram.createSocket('udp4');
client.on('error', function (err) {
    logger.logError("\n" + '===== socket error - ' + err + "\n");
});

client.on('close', function () {
    // console.log('socket connection closed');
});

let lastTime = new Date().getTime();

function openDoor(host, port, no) {
    const now = new Date().getTime();
    logger.logInfo("\n" + '===== THE LAST TIME OF OPEN THE DOOR: ' + (now - lastTime) + "ms =====" + "\n");
    // 控制一下2s之内执行一次
    if (Math.abs(now - lastTime) < 2000) {
        return;
    }
    // const client = dgram.createSocket('udp4');
    // client.on('error', function (err) {
    //     logger.logError("\n" + '===== socket error - ' + err + "\n");
    // });
    //
    // client.on('close', function () {
    //     // console.log('socket connection closed');
    // });

    // 01表示1秒后off，最大99秒
    port = port || 5000;
    no = no || '1:01';
    if (no) {
        lastTime = new Date().getTime();
        client.send('on' + no, port, host);
    }
}

exports.openDoor = openDoor;
